package com.marvels.financial.loan.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.consum.FinancialConsumerProductApi;
import com.marvels.financial.loan.dao.McfeCustomerRepaymentPlanDao;
import com.marvels.financial.loan.dao.McfeDebtorAmountInfoTmpDao;
import com.marvels.financial.loan.dao.McfeDebtorRepaymentInfoTmpDao;
import com.marvels.financial.loan.dto.McfeDebtorAmountInfoTmpDTO;
import com.marvels.financial.loan.dto.McfeDebtorRepaymentInfoTmpDTO;
import com.marvels.financial.loan.dto.McptChannelDto;
import com.marvels.financial.loan.service.CollectionReadyInfoApi;
import com.marvels.financial.loan.service.CollectionReadyInfoSenderService;

@Service
public class CollectionReadyInfoImpl implements CollectionReadyInfoApi {

	@Autowired
	private CollectionReadyInfoSenderService senderService;

	@Autowired
	private FinancialConsumerProductApi productApi;

//	@Autowired
//	private CommonProperties commonProperties;

	@Autowired
	private McfeCustomerRepaymentPlanDao planDao;

	@Autowired
	private McfeDebtorAmountInfoTmpDao mcfeDebtorAmountInfoTmpDao;
	
	@Autowired
	private McfeDebtorRepaymentInfoTmpDao mcfeDebtorRepaymentInfoTmpDao;
	
	// @Override
	// public void getCollectionReadyInfo() {
	// // 查询出所有渠道信息
	// try {
	// List<McptChannelDto> channelList = productApi.mcptChannelAllInfo(null);
	// List<String> list = null;
	// String intelligent = commonProperties.getIntelligentCollectionChannel();
	// if(StringUtils.isEmpty(intelligent)){//为空
	// list=new ArrayList<String>();
	// String[] strings = intelligent.split(",");
	// List<String> stringList = Arrays.asList(strings);
	// if (channelList != null && channelList.size() > 0) {
	// for (McptChannelDto dto : channelList) {
	// if (stringList != null && stringList.size() > 0) {
	// for (String s : stringList) {
	// if (dto.getPatternCode().equals(s)) {
	// list.add(dto.getChannelCode());
	// }
	// }
	// }
	// }
	// }
	// }
	//
	//
	//
	// // 查询出当天的逾期信息
	// List<McfeCustomerRepaymentPlanDTO> planList =
	// planDao.selectCurrentOverdueInfo(list);
	// if (planList == null || planList.size() < 1) {
	// MarvelsLogUtil.getInstance().info(">>>>>>>>当天无逾期还款计划信息");
	// return;
	// }
	//
	// // 循环当天的逾期信息 查询出当前逾期信息的进件信息 联系人信息
	// for (McfeCustomerRepaymentPlanDTO planDTO : planList) {
	// // 查询出当前loanId的进件信息
	// String loanId = planDTO.getLoanId();
	// McamLoanApplyInfoDTO applyInfoDTO = new McamLoanApplyInfoDTO();
	// applyInfoDTO.setLoanId(loanId);
	// applyInfoDTO = approveApi.selectLoanApplyInfo(applyInfoDTO);
	// McdrDebtorAccount account = new McdrDebtorAccount();
	// String businessCode = DateUtils.getYYYYMMDDHHMMSS(new Date())
	// + UUID.randomUUID().toString().replace("-", "").substring(0, 4);
	// account.setBusinessCode(businessCode);
	// account.setLoanId(loanId);
	// account.setDebtorName(applyInfoDTO.getCustName());// 姓名
	// account.setDebtorIdNo(applyInfoDTO.getCustCardNo());// 身份证号
	// account.setMarriage(applyInfoDTO.getMaritalStatus());//婚姻状况
	// account.setCareer(applyInfoDTO.getCompanyPositionType());//职业
	// account.setDebtorTelephone1(applyInfoDTO.getMobileNo());//手机号码1
	// account.setDebtorTelephone2("");//手机号码2
	// account.setPermAddr(applyInfoDTO.getCustCardAddress());//户籍地址
	// account.setHomeAddr(applyInfoDTO.getCurHomeAddress());//家庭住址
	// account.setWorkUnit(applyInfoDTO.getCompanyName());//工作单位
	// account.setWorkUnitaddr(applyInfoDTO.getCompanyAddress());//工作单位地址
	// account.setUnitPhone(applyInfoDTO.getCompanyTel());//单位电话
	// account.setSchool("");//就读学校
	// account.setSchoolAddr("");//就读学校地址
	// account.setWeixin("");//微信号码
	// account.setQq("");//QQ号码
	// account.setEmail(applyInfoDTO.getEmail());//邮箱
	// account.setWithdrawType("");//借款类型：线上贷款、消费金融、房产抵押
	// account.setReceiveBankCardNo(applyInfoDTO.getReceiveAcctNo());//提现卡号
	// account.setReceiveBankName(applyInfoDTO.getReceiveBankName());//提现卡总行名称
	// account.setReceiveBankNo(applyInfoDTO.getReceiveBankHead());//提现卡总行联行号
	// account.setReceiveBankBranchNo(applyInfoDTO.getReceiveBankBranch());//提现卡分行名称
	// account.setReceiveBankBranchName(applyInfoDTO.getReceiveBankName());//提现卡分行联行号
	// account.setRepaymentBankCardNo(applyInfoDTO.getPaymentAcctNo());//还款卡号
	// account.setRepaymentBankName(applyInfoDTO.getPaymentBankName());//还款卡总行名称
	// account.setRepaymentBankNo(applyInfoDTO.getPaymentBankHead());//还款卡总行联行号
	// account.setRepaymentBankBranchName(applyInfoDTO.getPaymentBankName());//还款卡分行名称
	// account.setRepaymentBankBranchNo(applyInfoDTO.getPaymentBankBranch());//还款卡分行联行号
	// account.setContractNo(loanId);//提现合同号
	// //查询合同信息
	// McfeCustomerLoanContractDTO
	// contractDTO=contractDao.selectContractByLoanId(loanId);
	// account.setContractDate(contractDTO.getCreatedDate());//提现合同日期
	// account.setContractAmount(contractDTO.getAmount());//提现（合同）金额
	// account.setLoanOutDate(contractDTO.getCreatedDate());//提现（放款）日期
	// account.setLoanPeriods(applyInfoDTO.getApplyTerms()+"");//贷款期数
	// account.setPeriodAmount(planDTO.getPeriodAmount());//每期应还金额
	// account.setMortgageType("");//
	// account.setMortgage("");//抵押物品
	// account.setProvCode(applyInfoDTO.getCurHomeProvince());//提现所在地（省份）编码
	// account.setProvName(applyInfoDTO.getCurHomeProvinceName());//提现所在地（省份）名称
	// account.setCityCode(applyInfoDTO.getCurHomeCity());//提现所在地（城市）编码
	// account.setCityName(applyInfoDTO.getCurHomeCityName());//提现所在地（城市）名称
	// account.setAreaCode("");//提现所在地（区/县）编码
	// account.setAreaName("");//提现所在地（区/县）名称
	// account.setProductCode(applyInfoDTO.getProductType());//借款产品编码
	// account.setProductName(applyInfoDTO.getProductTypeName());//借款产品名称
	// account.setOverdueStartDate(planDTO.getOverdueStartDate());//逾期开始时间（账单日，正常还款最后一天）
	// account.setTotleUncleared(planDTO.getTotleUncleared());//未结清总笔数
	// account.setRepaymentPeriods(planDTO.getRepaymentPeriods());//已还期数
	// account.setOverduePeriods(planDTO.getOverduePeriods());//逾期期数
	// planDTO.setAccount(account);
	// // 查询出当前loanId的联系人信息
	// List<McamLoanApplyContactInfo> contactList = new
	// ArrayList<McamLoanApplyContactInfo>();
	// McamLoanApplyContactInfo contactInfo = new McamLoanApplyContactInfo();
	// contactInfo.setLoanId(loanId);
	// approveApi.selectContactByLoanId(contactInfo);
	// planDTO.setContactList(contactList);
	// }
	// CollectionReadyInfoDTO infoDTO = new CollectionReadyInfoDTO();
	// infoDTO.setPlanList(planList);
	//
	// // 查询所有的逾期信息的统计
	// List<McdrDebtorInfo> debtorInfoList = planDao.selectOverdueStatic(list);
	// infoDTO.setDebtorInfoList(debtorInfoList);
	//
	// // 查询出当天的逾期还款信息
	// List<McdrDebtorRepaymentInfo> repaymentInfoList =
	// planDao.selectCurrentOverduePaymentInfo(list);
	// infoDTO.setRepaymentInfoList(repaymentInfoList);
	//
	// // 将信息保存
	// String uuid = UUID.randomUUID().toString().replace("-", "");
	// McfeCollectInfoQueueDTO queueDTO = new McfeCollectInfoQueueDTO();
	// queueDTO.setBatchId(uuid);
	// queueDTO.setCollectContent(JSONObject.fromObject(infoDTO).toString());
	// queueDTO.setCreatedBy("system");
	// queueDTO.setCreatedDate(new Date());
	// queueDTO.setStatus(false);// 0 未消费 1已消费
	// queueDTO.setUpdatedBy("system");
	// queueDTO.setUpdatedDate(new Date());
	// int count = queueDao.insertSelective(queueDTO);
	// if (count < 1) {
	// throw new Exception("智能催收数据信息queue保存失败");
	// }
	// // 发送智能催收信息给催收系统 生成批次号推给催收子系统 催收子系统然后拉取
	// senderService.send(uuid);
	// } catch (Exception e) {
	// MarvelsLogUtil.getInstance().error(">>>>>>>>智能催收准备数据信息异常:", e);
	// //发邮件
	// }
	//
	// }

	// @Override
	// public String getReadyInfoByBatchId(String batchId) {
	// McfeCollectInfoQueueDTO queueDTO = new McfeCollectInfoQueueDTO();
	// queueDTO.setBatchId(batchId);
	// List<McfeCollectInfoQueueDTO> list = queueDao.selectByBatchId(queueDTO);
	// if (list == null || list.size() < 1) {
	// return "";
	// }
	// // 将状态置为已消费
	// queueDTO.setStatus(true);
	// queueDTO.setUpdatedBy("system");
	// queueDTO.setUpdatedDate(new Date());
	// queueDao.updateByBatchId(queueDTO);
	// return list.get(0).getCollectContent();
	// }

	@Override
	public void overdueStatic() {
		// 查询出所有渠道信息
		try {
			List<McptChannelDto> channelList = productApi.mcptChannelAllInfo(new McptChannelDto());
			List<String> list = null;
			String intelligent = CommonProperties.getIntelligentCollectionChannel();
			if (StringUtils.isNotEmpty(intelligent)) {// 不为空
				String[] strings = intelligent.split(",");
				List<String> stringList = Arrays.asList(strings);
				if (channelList != null && channelList.size() > 0) {
					list = new ArrayList<String>();
					for (McptChannelDto dto : channelList) {
						if (stringList != null && stringList.size() > 0) {
							for (String s : stringList) {
								if (dto.getPatternCode().equals(s)) {
									list.add(dto.getChannelCode());
								}
							}
						}
					}
				}
			}
			// 先将催收金额统计数据插入临时表
			while (true) {
				int overdueStatic = 0;
				overdueStatic = planDao.insertOverdueStatic(list);// 没有数据可插入
				if (overdueStatic < 1) {
					break;
				}
			}
			String uuid = UUID.randomUUID().toString().replace("-", "");
			// 更新催收用户逾期金额信息100条批次
			int count = mcfeDebtorAmountInfoTmpDao.updateBatchId(uuid);
			if (count < 1) {
				return;
			}
			List<McfeDebtorAmountInfoTmpDTO> amountInfoList = mcfeDebtorAmountInfoTmpDao.selectByBatchId(uuid);
			if (amountInfoList == null || amountInfoList.size() < 1) {
				return;
			}
			// 循环推送到mq
//			for (McfeDebtorAmountInfoTmpDTO dto : amountInfoList) {
//				senderService.send("collection_overdue_static_information", dto.getLoanId());
//			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>推送催收金额统计数据异常", e);
		}
		
	}

	@Override
	public McfeDebtorAmountInfoTmpDTO getOverdueStaticByLoanId(String loanId) {
		return mcfeDebtorAmountInfoTmpDao.selectByLoanId(loanId);
	}

	@Override
	public void debtorRepaymentInfo() {
		// 查询出所有渠道信息
		try {
			List<McptChannelDto> channelList = productApi.mcptChannelAllInfo(new McptChannelDto());
			List<String> list = null;
			String intelligent = CommonProperties.getIntelligentCollectionChannel();
			if (StringUtils.isNotEmpty(intelligent)) {// 不为空
				String[] strings = intelligent.split(",");
				List<String> stringList = Arrays.asList(strings);
				if (channelList != null && channelList.size() > 0) {
					list = new ArrayList<String>();
					for (McptChannelDto dto : channelList) {
						if (stringList != null && stringList.size() > 0) {
							for (String s : stringList) {
								if (dto.getPatternCode().equals(s)) {
									list.add(dto.getChannelCode());
								}
							}
						}
					}
				}
			}
			// 先将催收用户人工还款信息插入临时表
			while (true) {
				int overdueStatic = 0;
				overdueStatic = planDao.insertDebtorRepaymentInfo(list);// 没有数据可插入
				if (overdueStatic < 1) {
					break;
				}
			}
			String uuid = UUID.randomUUID().toString().replace("-", "");
			// 更新催收用户人工还款信息100条批次
			int count = mcfeDebtorRepaymentInfoTmpDao.updateBatchId(uuid);
			if (count < 1) {
				return;
			}
			List<McfeDebtorRepaymentInfoTmpDTO> repaymentInfoList = mcfeDebtorRepaymentInfoTmpDao.selectByBatchId(uuid);
			if (repaymentInfoList == null || repaymentInfoList.size() < 1) {
				return;
			}
			/*// 循环推送到mq
			for (McfeDebtorRepaymentInfoTmpDTO dto : repaymentInfoList) {
				senderService.send("collection_debtor_repayment_information", dto.getLoanId());
			}*/
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>推送催收用户人工还款信息异常", e);
		}
	}

	@Override
	public McfeDebtorRepaymentInfoTmpDTO getdebtorRepaymentByLoanId(String loanId) {
		return mcfeDebtorRepaymentInfoTmpDao.selectByLoanId(loanId);
	}
}
